<?php

namespace App\Http\Resources;

use App\Repositories\QuizRepository;

use Illuminate\Http\Resources\Json\JsonResource;

class QuizFull extends Quiz
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        $players = $this->resource->players()->paginate()->toArray();
        $isCreater = $this->user_id == request()->user()->id;
        $isPublic = $isCreater ? true : $this->is_public;

        $statement = null;
        if ($isPublic && $this->status == QuizRepository::QUIZ_STATUS_FINISHED) {
            $explanation = data_get($this->statement, 'explanation');
            $lose = array_get($explanation, QuizRepository::QUIZ_ITEM_RESULT_LOSE, 0)
                + array_get($explanation, QuizRepository::QUIZ_ITEM_RESULT_LOSE_HALF, 0);
            $win = array_get($explanation, QuizRepository::QUIZ_ITEM_RESULT_WIN, 0)
                + array_get($explanation, QuizRepository::QUIZ_ITEM_RESULT_WIN_HALF, 0);
            $statement = collect([
                'result' => ($this->statement->copper < 0 ? __('generic.lose')
                        : __('generic.win')) . abs($this->statement->copper),
                'win' => $win,
                'lose' => $lose,
            ]);
        }

        return array_merge(parent::toArray($request), [
            'type' => $this->type,
            'is_creater' => $isCreater,
            'result' => $this->result,
            'items' => QuizItem::collection($this->itemsWithCurrentBets, $isPublic),
            'group' => new GroupWithHasJoined($this->cachedGroup),
            'players' => [
                'data' => $players['data'],
                'total' => $players['total'],
            ],
            'bet_result' => $statement,
            'links' => [
                'self' => route('quiz', ['quiz' => $this->id]),
                'announce' => route('announce', ['quiz' => $this->id]),
                'close' => route('quiz_close', ['quiz' => $this->id]),
                'bet_result' => route('quiz_result', ['quiz' => $this->id]),
            ],
            'is_public' => (int)$this->is_public,
            'copper_limit' => $this->copper_limit,
            'stop_at' => format_datetime_with_no_second($this->stop_at),
        ]);
    }
}
